#    Titan Music Player
#    Copyright (C) 2008  Chris "vbraun" Dopilka
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

import mutagen.oggvorbis
import os
import cPickle

class Library:
	def addNew(self,dir):
		#only checks for .ogg right now
		music = []
		suffix = (".ogg")
		#finds all files with suffix in all subfolders
		for root, dirs, file in os.walk(dir,topdown=False):
			for item in file:
				if str(item).endswith(suffix):
					music.append(os.path.join(root,item))
		
		for file in music:
			#get tags of file
			tags = mutagen.oggvorbis.Open(file)
			#futureLine is set up file;,tagList[0];,tagList[1] etc..
#			futureLine = file + ";,"
			shortTags = []
			for tag in self.tagList:
				if tags.has_key(tag):
					shortTags.append(tags[tag][0])
					#print futureLine
				else:
					#incase a tag isn't present
					shortTags.append(u'NONE')
			#catch and skip more weird unicode crap and write to file
			if shortTags[1] != u'NONE':
				try:
					key = shortTags[0] + u';,' + shortTags[1]
					value = shortTags[2] + u';,' + shortTags[3] + u';,' + unicode(file)
					
					if not self.randomDict.has_key(key):
						self.randomDict[key] = []
					try:
						self.randomDict[key].append(value)
					except:
						print shortTags
				except:
					print "fail"
		
		for key in self.randomDict.keys():
			self.randomDict[key].sort()
		#prepare text file
		library = open('lib.txt','w')		
		cPickle.dump(self.randomDict,library)
		library.close

	def generateList(self):
		#open file and read
		library = open('lib.txt','rb')
		self.randomDict = cPickle.load(library)
		library.close()
		

	def __init__(self,args,dir,tags):
		# only make library if asked for
		self.tagList = tags
		self.realDir = dir
		self.randomDict = {}
		if args == "reload":
			self.addNew(dir)
		if not self.randomDict:
			self.generateList()
